package com.icesoft.base.manager.service.system;

import com.icesoft.base.manager.base.BaseService;
import com.icesoft.base.manager.dao.impl.OrgQueryScopeFilter;
import com.icesoft.base.manager.entity.security.RelSysRoleOrg;
import com.icesoft.base.manager.entity.security.SysRole;
import com.icesoft.base.manager.entity.system.SysOrg;
import com.icesoft.base.manager.helper.DataScopeEnum;
import com.icesoft.base.manager.service.security.SysRoleService;
import com.icesoft.core.common.helper.TreeBean;
import com.icesoft.core.dao.criteria.QueryBuilder;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class SysOrgService extends BaseService<SysOrg> {
    private SysRoleService sysRoleService;

    public boolean checkCompanyCanDelete(int companyId) {
        return isExist(QueryBuilder.get("companyId", companyId).limit(1));
    }

    public List<TreeBean> toTreeBean(List<SysOrg> orgs) {
        return toTreeBean(orgs, null);
    }

    public List<TreeBean> toTreeBean(List<SysOrg> orgs, List<Integer> checkedList) {
        List<TreeBean> trees = new ArrayList<>();
        for (SysOrg org : orgs) {
            TreeBean bean = new TreeBean();
            if (checkedList != null && checkedList.contains(org.getId())) {
                bean.setChecked(true);
            }
            bean.setName(org.getName());
            bean.setId(String.valueOf(org.getId()));
            bean.setpId(String.valueOf(org.getPid()));
            trees.add(bean);
        }
        return trees;
    }

    /**
     * 查询orgId对应部门可以查看的范围
     */
    public List<SysOrg> findByRoleId(int roleId) {
        if (roleId == 0) {
            return new ArrayList<>();
        }
        QueryBuilder queryBuilder = QueryBuilder.get().asc("pid").desc("id");
        queryBuilder.joinOn(RelSysRoleOrg.class, "r", "orgId")
                .andEq("r.roleId", roleId);
        List<SysOrg> list = find(queryBuilder);
        return list;
    }

    /**
     * 查询orgId对应部门可以查看的范围
     */
    public List<SysOrg> findByUserId(int userId, int userOrgId) {
        if (userId == 0) {
            return new ArrayList<>();
        }
        List<SysRole> sysRoles = sysRoleService.findByUserId(userId);
        QueryBuilder queryBuilder = QueryBuilder.get().asc("pid").desc("id");
        DataScopeEnum.runScopeFilter(sysRoles, new OrgQueryScopeFilter(queryBuilder.getFromBuilder(), load(userOrgId)));
        return find(queryBuilder);
    }

    public Set<Integer> findOrgIdsByUserId(int userId, int userOrgId){
        return findByUserId(userId, userOrgId).stream().map(SysOrg::getId).collect(Collectors.toSet());
    }

    /**
     * 判断部门名是否存在
     */
    public boolean isExistByPidAndName(int pid, String name) {
        return isExist(QueryBuilder.get("pid", pid).andEq("name", name));
    }

    /**
     * 查找pid下一级所有部门，不包括及以下
     */
    public List<SysOrg> findSubOne(int pid) {
        return find(QueryBuilder.get("pid", pid).desc("id"));
    }

    public List<SysOrg> findByCompanyId(int companyId) {
        return find(QueryBuilder.get("companyId", companyId).asc("pid").desc("id"));
    }

    /**
     * 查找pid下所有部门及以下
     */
    public List<SysOrg> findSubAll(int pid) {
        if (pid == 0) {
            return findAll();
        }
        List<SysOrg> orgs = new ArrayList<>();
        Stack<Integer> stack = new Stack<>();
        stack.add(pid);
        while (!stack.isEmpty()) {
            int subPid = stack.pop();
            List<SysOrg> sub = findSubOne(subPid);
            orgs.addAll(sub);
            for (SysOrg o : sub) {
                stack.push(o.getId());
            }
        }
        return orgs;
    }

}
